package ubi.com.wifitest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.util.List;

/**
 * wifi管理器
 *
 * @author eli chang
 */
public class WifiAdmin {

    private static final String TAG = "WifiAdmin";
    //设备SSID和密码
    public static final String SSID = "SNX_LOGIN";
    public static final String PWD = "987654321";

    private Context context;
    private WifiManager wifiManager;
    //状态更新接口
    private OnWifiResult onScanWifiResult;
    //wifi状态接收器
    private WifiScanReceiver wifiScanReceiver;
    //网络状态接收器
    private NetStatusReceiver wifiStatusReceiver;
    //wifi配置信息
    private List<WifiConfiguration> wifiConfigurations;

    public WifiAdmin(Context context) {
        this.context = context;
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiConfigurations = wifiManager.getConfiguredNetworks();
        //开始监听
        startReceiver();
    }

    /**
     * 开始监听WIFI状态
     */
    private void startReceiver() {
        try {
            wifiStatusReceiver = new NetStatusReceiver();
            context.registerReceiver(wifiStatusReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        } catch (Exception e) {
        }
    }

    /**
     * 取消监听WIFI状态
     */
    public void stopReceiver() {
        try {
            context.unregisterReceiver(wifiStatusReceiver);
        } catch (Exception e) {
        }
    }

    /**
     * 获取WIFI连接信息
     *
     * @return
     */
    public boolean isConnectWithAP() {
        if (wifiManager != null) {
            WifiInfo info = wifiManager.getConnectionInfo();
            return info.getSSID().equals("\"" + SSID + "\"");
        }
        return false;
    }

    /**
     * 开启wifi设备
     */
    public void enableWifiDevice() {
        if (wifiManager != null && wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
            wifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 设置接口
     *
     * @param onScanWifiResult
     */
    public void setOnScanWifiResult(OnWifiResult onScanWifiResult) {
        this.onScanWifiResult = onScanWifiResult;
    }

    /**
     * 判断WIFI是否可用
     *
     * @return
     */
    public boolean isWifiEnable() {
        if (wifiManager != null) {
            return wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED;
        }
        return false;
    }

    /**
     * 开始扫描AP
     */
    public void startScan() {
        if (wifiManager != null && context != null) {
            try {
                wifiManager.startScan();
                wifiScanReceiver = new WifiScanReceiver();
                context.registerReceiver(wifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            } catch (Exception e) {
            }
        }
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        if (wifiManager != null && context != null) {
            try {
                context.unregisterReceiver(wifiScanReceiver);
            } catch (Exception e) {
            }
        }
    }

    /**
     * 从WIFI系统配置里获取指定网络ID
     *
     * @param SSID
     */
    private int isExist(String SSID) {
        if (wifiManager == null)
            return -1;
        wifiConfigurations = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration configuration : wifiConfigurations) {
            if (configuration.SSID.equals(SSID)) {
                return configuration.networkId;
            }
        }
        return -1;
    }

    /**
     * 连接到指定AP
     *
     * @param wifiConfiguration
     * @return
     */
    public boolean connectToAP(WifiConfiguration wifiConfiguration) {
        if (wifiManager != null) {
            wifiManager.disconnect();
            int id = isExist(wifiConfiguration.SSID);
            if (id < 0)
                id = wifiManager.addNetwork(wifiConfiguration);
            boolean result = wifiManager.enableNetwork(id, true);
            return result;
        }
        return false;
    }

    /**
     * WIFI状态接收者
     */
    public class NetStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isWifiConnected = false;
            //获取网络间接状态
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiStateInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiStateInfo != null) {
                isWifiConnected = wifiStateInfo.isConnectedOrConnecting();
            }
            //当前wifi信息
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            if (isWifiConnected && wifiInfo.getSSID().equals("\"" + SSID + "\"")) {
                //连接到设备
                if (onScanWifiResult != null) {
                    onScanWifiResult.onConnectWithAP();
                }
            } else if (!isWifiConnected || !wifiInfo.getSSID().equals("\"" + SSID + "\"")) {
                //未连接到设备
                if (onScanWifiResult != null) {
                    onScanWifiResult.onDisconnectWithAP();
                }
            }
        }
    }

    /**
     * 扫描WIFI的接收器
     */
    public class WifiScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (onScanWifiResult != null) {
                onScanWifiResult.onGetScanResult(wifiManager.getScanResults());
            }
        }
    }

    /**
     * 扫描WIFI结果的回调接口
     */
    public interface OnWifiResult {
        void onGetScanResult(List<ScanResult> values);

        void onDisconnectWithAP();

        void onConnectWithAP();
    }
}